package com.android.lovertest;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class LoverTest extends Activity {
	private static final int UPDATE = 0;
	private static final int MenuItem1 = Menu.FIRST + 1;
	private static final int MenuItem2 = Menu.FIRST + 2;

	enum GameState {
		Running, Pause, Stop
	};

	public static final int gvGamePics[] = { R.drawable.game1,
			R.drawable.game2, R.drawable.game3, R.drawable.game4,
			R.drawable.game5, R.drawable.game6, R.drawable.game7,
			R.drawable.game8, R.drawable.game9 };

	public static int gamePics[];

	private GridView gv;
	private GameGridViewAdapter ggvAdapter;
	
	private int score;
	private int time;
	private int correctindex;
	
	private TextView tvScore;
	private TextView tvTime;
	
	private GameState gameState;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				update();
				break;

			default:
				break;
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		initGame();

		initView();

		startGame();
	}
	

	public void initView() {
		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);

		tvScore = new TextView(this);
		tvScore.setText("Score : " + score);
		ll.addView(tvScore);

		tvTime = new TextView(this);
		tvTime.setText("Time : " + time);
		ll.addView(tvTime);

		gv = new GridView(this);
		gv.setNumColumns(3);
		ggvAdapter = new GameGridViewAdapter(this);
		gv.setAdapter(ggvAdapter);

		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (gameState != GameState.Running) {
					return;
				}
				
				if (arg2 == correctindex) {
					score += 4;
					tvScore.setText("Score : " + score);
					((ImageView)(gv.getChildAt(arg2))).setImageResource(R.drawable.yes1);
				} else {
					score -= 2;
					tvScore.setText("Score : " + score);
					((ImageView)(gv.getChildAt(arg2))).setImageResource(R.drawable.lost1);
				}
			}
		});

		ll.addView(gv);

		setContentView(ll);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MenuItem1, 1, "MenuItem1");
		menu.add(0, MenuItem2, 2, "MenuItem1");
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		if (gameState == GameState.Running) {
			menu.getItem(0).setTitle("pause");
			menu.getItem(1).setTitle("stop");
		} else if (gameState == GameState.Pause) {
			menu.getItem(0).setTitle("start");
			menu.getItem(1).setTitle("stop");
		} else if (gameState == GameState.Stop) {
			menu.clear();
			menu.add(0, MenuItem1, 1, "restart");
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case MenuItem1:
			if (gameState == GameState.Running) {
				pauseGame();
			} else if (gameState == GameState.Pause) {
				startGame();
			} else if (gameState == GameState.Stop) {
				reStartGame();
			}
			break;

		case MenuItem2:
			if (gameState == GameState.Running) {
				stopGame();
			} else if (gameState == GameState.Pause) {
				stopGame();
			} else if (gameState == GameState.Stop) {
				// ...
			}
			break;

		default:
			break;
		}

		return true;
	}


	public void initGame() {
		if (gamePics == null) {
			gamePics = new int[gvGamePics.length];
		}

		for (int i = 0; i < gvGamePics.length; i++) {
			gamePics[i] = gvGamePics[i];
		}

		int hostindex = this.getIntent().getIntExtra(
				ChooseHostActivity.HOSTINDEX, -1);
		if (hostindex != -1) {
			int rnum = new Random(System.currentTimeMillis())
					.nextInt(gamePics.length);
			Log.d("TAG", "rnum=" + rnum + ", hostindex=" + hostindex);
			gamePics[rnum] = ChooseHostActivity.gvHostPics[hostindex];
			correctindex = rnum;
		}

		score = 0;
		time = 30;
	}

	public void startGame() {
		gameState = GameState.Running;
		handler.sendEmptyMessageDelayed(UPDATE, 1000);
	}

	public void reStartGame() {
		startActivity(new Intent(this, ChooseHostActivity.class));
		finish();
	}

	public void pauseGame() {
		gameState = GameState.Pause;
	}

	public void stopGame() {
		gameState = GameState.Stop;
		
		ImageView iv = new ImageView(this);
		
		if(this.score > 48) {
			iv.setBackgroundResource(R.drawable.loverscore);
		} else {
			iv.setBackgroundResource(R.drawable.lostlove);
		}
		
		setContentView(iv);
	}

	public void update() {
		if (gameState != GameState.Running) {
			return;
		}

		time--;
		tvTime.setText("Time : " + time);

		Random random = new Random(System.currentTimeMillis());

		for (int i = 0; i < gamePics.length; i++) {
			int a = random.nextInt(gamePics.length);
			int b = random.nextInt(gamePics.length);

			// Log.d("TAG", "change a and b [" + a + "," + b + "]");
			if (a != b) {
				int tmp = gamePics[a];
				gamePics[a] = gamePics[b];
				gamePics[b] = tmp;

				if (a == correctindex) {
					correctindex = b;
				} else if (b == correctindex) {
					correctindex = a;
				}
			}
			// Log.d("TAG", "correctindex [" + correctindex + "]");
		}
		
		gv.setAdapter(ggvAdapter);

		if (time > 0) {
			handler.sendEmptyMessageDelayed(UPDATE, 1000);
		} else {
			stopGame();
		}
	}
}

class GameGridViewAdapter extends BaseAdapter {

	private Context context;

	public GameGridViewAdapter(Context context) {
		this.context = context;
	}

	@Override
	public int getCount() {
		return LoverTest.gamePics.length;
	}

	@Override
	public Object getItem(int arg0) {
		return LoverTest.gamePics[arg0];
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {

		ImageView iv = null;

		if (arg1 == null) {
			iv = new ImageView(context);
			iv.setPadding(2, 2, 2, 2);
		} else {
			iv = (ImageView) arg1;
		}

		iv.setImageResource(LoverTest.gamePics[arg0]);
		return iv;
	}
	
}